package com.gejia.qixishare.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gejia.qixishare.entity.UploadRecordDO;
import com.gejia.qixishare.exceptions.BusinessException;
import com.gejia.qixishare.service.FileMd5RecordService;
import com.gejia.qixishare.service.UploadRecordService;
import com.gejia.qixishare.utils.FileReadWriteUtils;
import com.gejia.qixishare.utils.oss.AliyunOSSUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zy
 * @since 2020-08-22
 */
@RestController
@RequestMapping("//qixi")
public class UploadRecordController {

    @Autowired
    private AliyunOSSUtils aliyunOSSUtils;

    @Autowired
    private UploadRecordService uploadRecordService;

    @Autowired
    private FileMd5RecordService fileMd5RecordService;

    private final String sentencePath = "static/sentence.txt";

    @PostMapping("/upload")
    public Map<String, Object> uploadPicture(@RequestParam("img") MultipartFile img) throws IOException {
        Map<String, Object> resp = new HashMap<>();
        String md5Hex1 = DigestUtils.md5Hex(img.getInputStream());
        System.err.println("MD5:" + md5Hex1);
//        这里通过获取文件的MD5判断文件是不是已经上传过了，如果已经上传过OSS就不需要重新上传，拿到文件的路径就好
        String ossFilePath = this.fileMd5RecordService.getOSSPathIfExist(img);
        if(ossFilePath != null){
           List<UploadRecordDO> uploadRecordDOList = uploadRecordService.list(new QueryWrapper<UploadRecordDO>().eq("picture_path", ossFilePath));
           if(uploadRecordDOList.size() > 0){
               int imgKey = uploadRecordDOList.get(0).getId();
               resp.put("result", "OK");
               resp.put("img_key", imgKey);
               return resp;
           }
        }
        String path;
        try {
             path =  aliyunOSSUtils.fileUpload(img);
        }catch (BusinessException exception){
            resp.put("result", "FAILED");
            resp.put("msg", exception.getMessage());
            System.err.println(exception.getMessage());
            return resp;
        }
        UploadRecordDO recordDO = new UploadRecordDO();
        recordDO.setPicturePath(path);
        recordDO.setSentenceIndex(1);
        String md5Hex = DigestUtils.md5Hex(img.getInputStream());
        uploadRecordService.saveUploadRecord(recordDO, md5Hex);
        resp.put("result", "OK");
        resp.put("img_key", recordDO.getId());
        return resp;
    }


    @GetMapping("/shareCount")
    public Map<String, Object> getShareTotolCount(){
        int num = uploadRecordService.count();
        Map<String, Object> resp = new HashMap<>();
        resp.put("result", "OK");
        resp.put("totalCount", num);
        return resp;
    }

    @GetMapping("/getShareInfo")
    public Map<String, Object> getShareInfo(@RequestParam("id") long id){
        UploadRecordDO recordDO = uploadRecordService.getById(id);
        Map<String, Object> resp = new HashMap<>();
        resp.put("result", "OK");
        resp.put("img_path", recordDO.getPicturePath());
        resp.put("sentence_index", recordDO.getSentenceIndex());
        return resp;
    }

    @GetMapping("/randomSentence")
    public Map<String, Object> generateRandomSentence() throws FileNotFoundException {
        Map<String, Object> resp = new HashMap<>();
        File upload = new File(System.getProperty("user.dir"));
        String classPath = upload.getPath();
//        String classPath = path.getAbsolutePath();
        System.err.println("classPath:"+classPath);
        String filePath = classPath + "/" + this.sentencePath;
        try {
            int totalLineNumber = FileReadWriteUtils.getFileLineNumber(filePath);
            Random random = new Random();
            int maxNum = 10;
            int i = 0;
            String sentence = "";
//            防止一次没有获取到内容，重新试几次
            while (i < maxNum){
                int lineNumber = random.nextInt(totalLineNumber);
                sentence = FileReadWriteUtils.readFileAtLineNumber(filePath, lineNumber);
                if(!sentence.trim().isEmpty()){
                    break;
                }
                ++i;
            }
            resp.put("result", "OK");
            resp.put("sentence", sentence);
        } catch (IOException e) {
            e.printStackTrace();
            resp.put("result", "FAILED");
            resp.put("errorMsg", e.getMessage());
        }
        return resp;
    }
}
